package com.aruba.socketlibrary.protocol;

import android.os.Environment;
import android.util.Log;

import com.aruba.socketlibrary.entity.SerialFile;
import com.aruba.socketlibrary.entity.SerialFileReq;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by aruba on 2017/10/20.
 */

public class FileManger {
    private static final String tag = FileManger.class.getSimpleName();
    private List<String> serialFiles = new ArrayList<>();
    private SerialFileReq nowSerialFile;
    private SerialFile oldSerialFile;
    public static String path = Environment.getExternalStorageDirectory() + "/newapk";

    public void add(SerialFile serialFile) {
        if (serialFile == null) {
            return;
        }

        if (!serialFiles.contains(serialFile.getFileName())) {
            deleteExistFile(serialFile.getFileName());//删除存在文件
            serialFiles.add(serialFile.getFileName());
        }
//        else if (oldSerialFile != null && oldSerialFile.getPacketIndex() + oldSerialFile.getPacketLength() != serialFile.getPacketIndex()) {//判断索引
//            Log.i(tag, "文件索引出错");
//            return;
//        }

        oldSerialFile = serialFile;
        createFileWithByte(serialFile.getData(), serialFile.getFileName());
    }

    /**
     * 清除坏文件
     */
    public void clearBadFile() {
        File file;
        for (String fileName : serialFiles) {
            file = new File(path, fileName);
            if (file.exists()) {
                file.delete();
            }
        }
        serialFiles.clear();
    }

    public void complite(String fileName) {
        serialFiles.remove(fileName);
    }

    public boolean isComplite() {
        if (nowSerialFile != null && nowSerialFile.getSize() == getFileSize()) {
            Log.i(tag, "文件传输完成");
            return true;
        }

        return false;
    }

    /**
     * 删除存在文件
     *
     * @param fileName
     */
    private void deleteExistFile(String fileName) {
        File file = new File(path, fileName);

        if (file.exists()) {
            file.delete();
        }
    }

    public long getFileSize() {
        if (!isExist(nowSerialFile.getFileName())) {
            return 0;
        }

        File file = new File(path, nowSerialFile.getFileName());
        return file.length();
    }

    public boolean isExist(String fileName) {
        File file = new File(path, fileName);

        return file.exists();
    }

    public void setNowSerialFile(SerialFileReq nowSerialFile) {
        this.nowSerialFile = nowSerialFile;
    }

    public SerialFile getOldSerialFile() {
        return oldSerialFile;
    }

    /**
     * 根据byte数组生成文件
     *
     * @param bytes 生成文件用到的byte数组
     */
    private void createFileWithByte(byte[] bytes, String fileName) {
        /**
         * 创建File对象，其中包含文件所在的目录以及文件的命名
         */
        File file = new File(path, fileName);
        FileOutputStream outputStream = null;
        BufferedOutputStream bufferedOutputStream = null;
        try {
            // 如果文件不存在
            if (!file.exists()) {
                // 在文件系统中根据路径创建一个新的空文件
                file.getParentFile().mkdirs();
                file.createNewFile();
            }

            outputStream = new FileOutputStream(file, true);
            bufferedOutputStream = new BufferedOutputStream(outputStream);
            bufferedOutputStream.write(bytes);
            bufferedOutputStream.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭创建的流对象
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bufferedOutputStream != null) {
                try {
                    bufferedOutputStream.close();
                } catch (Exception e2) {
                    e2.printStackTrace();
                }
            }
        }
    }
}
